package com.sx.gataway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;


@Component
public class BlackListFilter implements GlobalFilter, Ordered {
    /**
     * 黑名单列表
     */
    private static List<String> list = new ArrayList<String>();

    static {
        list.add("127.0.0.1");
        list.add("192.168.1.16");
        list.add("0:0:0:0:0:0:0:1"); // IPv6 localhost
        list.add("localhost"); // 域名形式的localhost

    }

    /**
     * 过滤器逻辑
     *
     * @param exchange:封装了请求request和RESponse
     * @param chain:网关过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        
        // 获取远程地址
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String hostString = remoteAddress != null ? remoteAddress.getHostString() : "unknown";
        
        System.out.println("进入黑名单过滤器，访问者IP: " + hostString);
        
        if(list.contains(hostString)){
            System.out.println("IP地址 " + hostString + " 在黑名单中，拒绝访问");
            // 拒绝访问，返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "Access Denied: Your IP " + hostString + " is in the blacklist!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        System.out.println("IP地址 " + hostString + " 不在黑名单中，允许访问");
        return chain.filter(exchange);
    }


    /**
     * 定义过滤器执行的顺序，getOrder()里面的大小越小优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }


}
